package com.yxw.live_vod_boot.log;

import com.alibaba.fastjson.JSON;
import com.yxw.live_vod_boot.entity.YxVideoInterfaceLogEntity;
import com.yxw.live_vod_boot.enums.HsSdkEnum;
import com.yxw.live_vod_boot.service.LogService;
import com.yxw.live_vod_boot.utils.JsonUtils;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

/**
 * 上传火山引擎日志记录切面
 * liuxin
 * 2023.10.27
 */
@Aspect
@Component
@Slf4j
public class UploadLogAspect {

    @Autowired
    private LogService logService;

    // 定义ThreadLocal，用于保存请求信息
    private ThreadLocal<YxVideoInterfaceLogEntity> logThreadLocal = new ThreadLocal<>();

    /**
     * 切入方法入口路径
     */
    @Pointcut(value = "execution(* com.yxw.live_vod_boot.utils.VolcanoEngineUtil.callVideolSdk(..))")
    public void pointcut() {

    }

    //进入切入方法前执行
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        try {
            YxVideoInterfaceLogEntity log = new YxVideoInterfaceLogEntity();
            //写入参数
            Object[] args = joinPoint.getArgs();
            log.setRequestMsg(Arrays.toString(args));
            if(args.length>1){
                //接口信息
                HsSdkEnum sdkEnum = (HsSdkEnum) args[1];
                log.setIntfType(sdkEnum.getIdentifying());
                log.setIntfName(sdkEnum.getName());
                log.setBussId(String.valueOf((args[2])));
            }
            log.setCreateTime(new Date());
            log.setCallType(CommonConstant.ONE);
            logThreadLocal.set(log);
        }catch (Exception e){
            log.error("出口切面出错{}",e.getMessage());
        }
    }

    //切后方法后执行
    @AfterReturning(returning  = "result",pointcut = "pointcut()")
    public void AfterReturning(JoinPoint joinPoint,Object result) {
        try {
            YxVideoInterfaceLogEntity log = logThreadLocal.get();
            log.setResponseMsg(String.valueOf(result));
            log.setFlag(CommonConstant.ONE);
            logService.addUploadLog(log);
        }catch (Exception e){
            log.error("出口切面出错{}",e.getMessage());
        }
    }

    /**
     * 切口方法异常处理
     */
    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowing(Throwable e){
        try {
            YxVideoInterfaceLogEntity log = logThreadLocal.get();
            log.setFlag(CommonConstant.ZERO);
            log.setErrMsg(e.getMessage());
            logService.addUploadLog(log);
        }catch (Exception ee){
            log.error("出口切面出错{}",ee.getMessage());
        }
    }
}